//
//  SEGMenuListViewController.m
//  FrameworkTest
//
//  Created by 刘山 on 2018/4/8.
//  Copyright © 2018年 刘山. All rights reserved.
//

#import "SEGMenuListViewController.h"
#import "SEGMenuListManager.h"
#import "SEGSquareTableViewCell.h"
#import "SEGNewAlertView.h"
#import "SEGMenuSideslipView.h"
#import "SEGTencetAdTableViewCell.h"
#import "SEGCommunityShoppingMallView.h"
#import "SEGMenuListHotNewsTableViewCell.h"
#import "SEGMenuListCellManager.h"
#import <SEGMenus/SEGAutoTableView.h>
#import <SEGMenus/SEGPGCAdvertisementTableViewCell.h>

#if __has_include(<SEGMenus/SEGDisgroupHeaderView.h>)
#import <SEGMenus/SEGDisgroupHeaderView.h>
#else
#import "SEGDisgroupHeaderView.h"
#endif


@interface SEGMenuListViewController ()
<protocolAutoTableViewDelegaete,
SEGprotocolSEGSquareScrollViewDelegate,
SEGNewAlertViewDelegate,
UIScrollViewDelegate,
SEGProtocolCommunityShoppingMallViewDelegate,
SEGMenuListHotNewsTableViewCellDelegate>

/** cell高度缓存(保证估算高度的准确性) */
@property (nonatomic, strong)NSMutableDictionary *cellHightDict;
/**
 腾讯广告数据源
 */
@property (nonatomic, strong)NSArray<GDTNativeExpressAdView*> *expressAdViews;
/**
 统计腾讯广告渲染成功的次数
 */
@property (nonatomic, assign) NSInteger tencentAdRenderCount;

@property (nonatomic, strong) NSIndexPath *selectedIndexPath;
/**
 4.7.0新增，用于记录物业通知控件的坐标
 */
@property (nonatomic, strong) NSIndexPath *uPropertyIndex;

@end

@implementation SEGMenuListViewController
#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [[NSUserDefaults standardUserDefaults] setObject:@(YES) forKey:@"SEGUserDefaultsCanFreshPGCData"];
    self.view.backgroundColor = kColor_bg;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.tencentAdRenderCount = 5; //拉取腾讯广告的总数量
    
    [self segShowLocalDataAndRequestServerDataIsManualRefresh:NO];
    
    [self seg_initNotification];
    
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    //应用未开启时 收到远程通知 在此处进行跳转
    [[SEGUhomeMediator sharedInstance] seg_pushToViewControllerWithMessageInfo:nil];
    
    // [self segShowProfile];弹窗取消 2018-6-20，4.6.0
    
    if ([[SEGMenulist2Manager sharedManager].menuListTab.firstObject.action isEqualToString:self.action]) {
        NSString *key = [NSString stringWithFormat:@"%@WinFlag",kAccountUserID];
        if (![[[NSUserDefaults standardUserDefaults] valueForKey:key] isEqualToString:@"1"]) {//未获得注册或认证红包
            /// 请求检测注册用户是否获取分享礼物接口
            
            [[SEGCheckShareRecordManager sharedManager] requestCheckShareRecordCompleted:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull codeType, NSString * _Nonnull errorMessage) {
                if([codeType isEqualToString:@"0"]) {
                    // 红包卡卷
                    [[SEGUhomeMediator sharedInstance] seg_showRedWalletViewWithType:@{@"fromType":@(SEGRedWalletFromType_SignUp),
                                                                                       @"nav":self.navigationController
                                                                                       }];
                    //存储获奖状态
                    [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:key];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                }
            }];
            
        }
    }
}


- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - init
// 子类注意不要重写这个方法
- (void)seg_initNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addOrHideRedDot:) name:SEGAddReddotNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addOrHideRedDot:) name:SEGHiddenRedDotNotification object:nil];
    // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addOrHideRedDot:) name:SEGHiddenRedDotNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(uPropertyNotificationUpdate:) name:SEGConstUPropertyNotification object:nil];
}

#pragma mark - send request
/**
 * 展示本地数据、请求网络数据
 * @author Sam
 * @version 4.6.0
 * isManualRefresh: 是否手动刷新. 手动下拉刷新的话不需要加载本地缓存数据(因为未对菜单中邻里圈,社区活动等做缓存,在网络成功回调前会出现暂无内容页面)
 */
- (void)segShowLocalDataAndRequestServerDataIsManualRefresh:(BOOL)isManualRefresh {
    
    SEGAdvlistType adType = SEGAdvlistType_SY;
    if ([self.action isEqualToString:@"TAB_SERVICE"]) {
        adType = SEGAdvlistType_SERVER;
    }
    
    NSDictionary* hotParams = @{@"pageLimit":@"6",
                                @"pageNo":@"1"};
    WeakSelf;
    if (isManualRefresh) { // 手动下拉刷新, 无需展示缓存数据
        // 请求网络数据
        [weakSelf seg_requestMenuDataAndBussinessDataWithAdType:adType params:hotParams];
    } else {
        // 展示本地数据
        [self.menuListManager segAsyncGetLocalDataWithAction:self.action PositionType:adType settingsId:self.settingsId finished:^(BOOL hasTopLine, BOOL hasAd, BOOL hasCommonMenu, NSArray<SEGNeighborRollViewModel *> *topLine) {
            weakSelf.menuDataSource = [self.menuListManager.menuListDataArr mutableCopy];
            [weakSelf segResponseDataHasTopLine:hasTopLine HasAd:hasAd topLine:topLine];
            [weakSelf.tableView reloadData];
            [weakSelf refreshOtherData];
            // 请求网络数据
            [weakSelf seg_requestMenuDataAndBussinessDataWithAdType:adType params:hotParams];
        }];
    }
}

/**
 获取服务器菜单数据
 
 @param adType 广告类型
 @param hotParams 分页参数
 */
- (void)seg_requestMenuDataAndBussinessDataWithAdType:(SEGAdvlistType)adType params:(NSDictionary *)hotParams {
    WeakSelf;
    [self.menuListManager segReqqustMenuDataAndBusinessDataWithMenuSid:self.menuSid action:self.action PositionType:adType settingsId:self.settingsId hotNewsParams:hotParams targetVC:self Finished:^(BOOL hasTopLine, BOOL hasAd, BOOL hasCommonMenu, NSArray<SEGNeighborRollViewModel *> *topLine) {
        // 停止下拉刷新动画
        [weakSelf.tableView stopAnimatingWindmill];
        
        weakSelf.menuDataSource = [weakSelf.menuListManager.menuListDataArr mutableCopy];
        [weakSelf segResponseDataHasTopLine:hasTopLine HasAd:hasAd topLine:topLine];
        
        NSInteger refreshCount = weakSelf.menuListManager.pgcManager.freshCount;
        if (refreshCount > 0) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf segAlertWithContent:[NSString stringWithFormat:@"已为您加载%ld条内容",(long)refreshCount]];
            });
        }
        [weakSelf.tableView reloadData];
        [weakSelf refreshOtherData];
    }];
}
 
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.menuDataSource.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.menuDataSource[section] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SEGMenuListModel *model = self.menuDataSource[indexPath.section][indexPath.row];
    // 门禁 用于服务页刷新
    if (model.widgetType.integerValue == SEGEnumShowTypeDoorAccessControl) self.doorControlIndexPath = indexPath;
    // 物业通知 用于红点刷新
    if (model.widgetType.integerValue == SEGEnumShowTypePropertyNotification) self.uPropertyIndex = indexPath;
    // 融汇、海伦堡导航栏(70001)
    if (model.widgetType.integerValue == SEGEnumShowTypeNavigationBar ||
        model.widgetType.integerValue == SEGEnumShowTypeNavigationBarSYWY ||
        model.widgetType.integerValue == SEGEnumShowTypeNavigationBar_99001 ||
        model.widgetType.integerValue == SEGEnumShowTypeNavigationBar_99002 ||
        model.widgetType.integerValue == SEGEnumShowTypeNavigationBar_99003 ||
        model.widgetType.integerValue == SEGEnumShowTypeNavigationBar_99004) return [UITableViewCell new];
    // 邻里头条在首页不展示在菜单列表中
    if ([self.action isEqualToString:@"TAB_SHARE"] && model.widgetType.integerValue == SEGEnumShowTypeTopLine) return [UITableViewCell new];
    UITableViewCell *cell = [SEGMenuListCellManager menuList_tableView:tableView
                                                 cellForRowAtIndexPath:indexPath
                                                      sectionDataCount:[self.menuDataSource[indexPath.section] count]
                                                             menuModel:model
                                                 currentViewController:self
                                                                  info:NSStringFromClass([self class])];
    return cell;
}
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellHeight_key = [NSString stringWithFormat:@"%ld_%ld",(long)indexPath.section, (long)indexPath.row];
    [self.cellHightDict setObject:@(cell.frame.size.height) forKey:cellHeight_key];
}
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = kMenuListCell_estimatedHeight;
    NSString *cellHeight_key = [NSString stringWithFormat:@"%ld_%ld",(long)indexPath.section, (long)indexPath.row];
    height = [[self.cellHightDict objectForKey:cellHeight_key] floatValue];
    if (height == 0) height = kMenuListCell_estimatedHeight;
    return height;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 邻里头条在首页不展示在菜单列表中
    SEGMenuListModel *model = self.menuDataSource[indexPath.section][indexPath.row];
    if ([self.action isEqualToString:@"TAB_SHARE"] && model.widgetType.integerValue == SEGEnumShowTypeTopLine) return CGFLOAT_MIN;
    // 融汇导航栏(70001)
    if (model.widgetType.integerValue == SEGEnumShowTypeNavigationBar ||
        model.widgetType.integerValue == SEGEnumShowTypeNavigationBarSYWY ||
        model.widgetType.integerValue == SEGEnumShowTypeNavigationBar_99001 ||
        model.widgetType.integerValue == SEGEnumShowTypeNavigationBar_99002 ||
        model.widgetType.integerValue == SEGEnumShowTypeNavigationBar_99003 ||
        model.widgetType.integerValue == SEGEnumShowTypeNavigationBar_99004) return CGFLOAT_MIN;
    if (model.widgetType.integerValue == SEGEnumShowTypeAD) return model.advertisementData.totalHeight;
    if (model.widgetType.integerValue == SEGEnumShowTypeOwnershipDescription) return model.kitHeight;
    if (model.widgetType.integerValue == SEGEnumShowTypeCircleAndRect) return model.kitHeight;
    return UITableViewAutomaticDimension;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    SEGMenuListModel *model = self.menuDataSource[section].firstObject;
    if (model.widgetType.integerValue == SEGEnumShowTypeNavigationBar ||
        model.widgetType.integerValue == SEGEnumShowTypeNavigationBarSYWY ||
        model.widgetType.integerValue == SEGEnumShowTypeNavigationBar_99001 ||
        model.widgetType.integerValue == SEGEnumShowTypeNavigationBar_99002 ||
        model.widgetType.integerValue == SEGEnumShowTypeNavigationBar_99003 ||
        model.widgetType.integerValue == SEGEnumShowTypeNavigationBar_99004) return CGFLOAT_MIN;
    if ([model.disGroupIsShow integerValue] == 1) {
        if ([model.disGroupWidgetType integerValue] == SEGMenuGroupNormal) {
            SEGDisgroupHeaderViewModel *data = [[SEGDisgroupHeaderViewModel alloc]init];
            data.title = model.disGroupName;
            SEGDisgroupHeaderViewLayout *layout = [[SEGDisgroupHeaderViewLayout alloc]initWithData:data type:SEGEnumDisgroupHeaderViewType_NO];
            return layout.totalHeight;
        }
    }
    return CGFLOAT_MIN;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    SEGMenuListModel *model = self.menuDataSource[section].firstObject;
    // 组头逻辑
    if (model.widgetType.integerValue == SEGEnumShowTypeNavigationBar ||
        model.widgetType.integerValue == SEGEnumShowTypeNavigationBarSYWY ||
        model.widgetType.integerValue == SEGEnumShowTypeNavigationBar_99001 ||
        model.widgetType.integerValue == SEGEnumShowTypeNavigationBar_99002 ||
        model.widgetType.integerValue == SEGEnumShowTypeNavigationBar_99003 ||
        model.widgetType.integerValue == SEGEnumShowTypeNavigationBar_99004) return [UIView new];
    if ([model.disGroupIsShow integerValue] == 1) {
        if ([model.disGroupWidgetType integerValue] == SEGMenuGroupNormal) {
            SEGDisgroupHeaderViewModel *data = [[SEGDisgroupHeaderViewModel alloc]init];
            data.title = model.disGroupName;
            SEGDisgroupHeaderViewLayout *layout = [[SEGDisgroupHeaderViewLayout alloc]initWithData:data type:SEGEnumDisgroupHeaderViewType_NO];
            SEGDisgroupHeaderView *varDisgroupHeaderView = [[SEGDisgroupHeaderView alloc]initWithFrame:CGRectZero];
            [varDisgroupHeaderView setWithLayout:layout];
            return varDisgroupHeaderView;
        }
    }
    return [UIView new];
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    SEGMenuListModel *model = self.menuDataSource[section].firstObject;
    if (model.widgetType.integerValue == SEGEnumShowTypeFleaMarketing) {
        return 5.f;
    }
    if (model.widgetType.integerValue == SEGEnumShowTypeNeighbour_HLB) {
        return 15.f;
    }
    // 最后一行隐藏footer
    if (section == self.menuDataSource.count - 1) return CGFLOAT_MIN;
    if ([model.disGroupIsMargin integerValue] != 1) return kMenuListFooterView_Height;//组逻辑，判断是否展示组间的间隙
    if ([self.action isEqualToString:@"TAB_SHARE"] ||
        [self.action isEqualToString:@"TAB_SERVICE"] ||
        [self.action isEqualToString:@"TAB_ME"]) return 10.f;
    return kMenuListFooterView_Height;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    // 最后一行隐藏footer
    if (section == self.menuDataSource.count - 1) return [UIView new];
    UIView *footerView = [[UIView alloc] init];
    UIView *view = [[UIView alloc] init];
    view.frame = CGRectMake(0, 0, LYScreenWidth(), kMenuListFooterView_Height);
    view.backgroundColor = kColor_W;
    if ([self.action isEqualToString:@"TAB_SERVICE"]) view.backgroundColor = kColor_bg;
    [footerView addSubview:view];
    return footerView;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    SEGMenuListModel *model = self.menuDataSource[indexPath.section][indexPath.row];
    if (model.widgetType.integerValue == SEGEnumShowTypeCommunityActivity && model.activityModel) {
        NSDictionary *param = @{@"actId": ValueToString(model.activityModel.actId) ?: @"",
                                @"nav":self.navigationController
                                };
        // 内部请求了活动详情接口再跳转
        [[SEGUhomeMediator sharedInstance] seg_goToActivityManageDetailViewController:param];
        return;
    }
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [SEGAlertView removeRefrshTipsWithParentView:self.tableView];
}

#pragma mark - event response

#pragma mark - private methods
- (void)uPropertyNotificationUpdate:(NSNotification*)useerInfo {
    if (self.uPropertyIndex) {
        UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:self.uPropertyIndex];
        if ([cell isKindOfClass:NSClassFromString(@"SEGPropertyInformTableViewCell")]) {
            [self.tableView reloadRowsAtIndexPaths:@[self.uPropertyIndex] withRowAnimation:UITableViewRowAnimationNone];
        }
    }
}

- (void)segAlertWithContent:(NSString*)content {
    [SEGAlertView showRefrshTipsWithMessage:content parentView:self.tableView];
}

/**
 * 数据加载后的回调 - 给子类调用
 * @author Sam
 * @version 4.6.0
 * @param hasTopLine  邻里头条是否存在
 * @param HasAd  是否存在广告
 * @param topLine  邻里头条数据
 */
- (void)segResponseDataHasTopLine:(BOOL)hasTopLine HasAd:(BOOL)HasAd topLine:(NSArray<SEGNeighborRollViewModel *> *)topLine {
    
}

- (void)addOrHideRedDot:(NSNotification *)notification {
    if (notification.object) {
        NSArray *ids = notification.object;
        if (ids && [ids isKindOfClass:[NSArray class]]) {
            // TODO: Sam，4.6.0,观察闪屏是否因为这个造成的
            dispatch_async(dispatch_get_main_queue(), ^{
               [self.tableView reloadData];
            });
        }
    }
}

#pragma mark - 完善资料弹窗
-(void)segShowProfile {
    //弹出完善资料弹窗
    if ([SEGUtils isFirstLoad] == YES && [[SEGProfileManager sharedManager].profile.profileFinishFlag isEqualToString:@"0"]) {
        SEGNewAlertView *alertView = [[SEGNewAlertView alloc] init];
        alertView.labelLeft = YES;
        [alertView showWithAlertText:[NSString stringWithFormat:@"欢迎进入“%@”大本营，畅想智慧社区生活，快去完善资料让邻居更了解你，还可获得积分。",kAppName] delegate:self buttonTitlesArray:@[@"我再看看", @"现在去完善"]];
    }
}

- (void)segNewAlertView:(UIView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) { //再看看
        return;
    }
    if (buttonIndex == 1) { //完善资料
        [self.navigationController pushViewController:[[SEGUhomeMediator sharedInstance]seg_initSEGCompleteGenderInfoViewController:nil] animated:YES];
        return;
    }
}

// 停止刷新
- (void)segResponseStopFreshData {
}

- (BOOL)segViewTotalHeight:(CGFloat)totalHeight {
    return YES;
}
// 加载了菜单数据的时候 子类需要更新数据的逻辑处理
- (void)refreshOtherData {
    
}
//菜单接口下发调用子类
- (void)segResponseMenuListData {
}


#pragma mark - setter and getter
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = kColor_W;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
    }
    return _tableView;
}
- (SEGMenuListManager *)menuListManager {
    if(!_menuListManager) _menuListManager = [[SEGMenuListManager alloc] init];
    return _menuListManager;
}
- (NSMutableArray<NSMutableArray<SEGMenuListModel *> *> *)menuDataSource {
    if (!_menuDataSource) _menuDataSource = [[NSMutableArray<NSMutableArray<SEGMenuListModel*> *> alloc]init];
    return _menuDataSource;
}
- (NSMutableDictionary *)cellHightDict {
    if (!_cellHightDict) _cellHightDict = [NSMutableDictionary new];
    return _cellHightDict;
}


@end
